define(['angularAMD', 'module/moduleB/program/B02/B0231/B0231Service'], function (angularAMD) {
    angularAMD.service('B0233Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog', 'B0231Service','$timeout',
        function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $B0231Service, $timeout) {
            this.init = function(options){
                //option = {stationMachine};
                let need_check = false; // 20231218 add by shiwl for M#0151498: 力邦合信，正式区。人员技能检核以后无记录写入数据库
                let check_member = '';//強制通過檢核人員 20201012 add by Oliver for M#78622
                var employeeWorkReason = config.cache.sys_parameter.EmployeeWorkReason;

                 // 是否需要人員上/下工原因，1. 上工 2. 下工 3. 皆需要
                function isNeedWorkReason(work_mode){
                    var result = false;

                    if(employeeWorkReason){
                        if(work_mode == 'U' && employeeWorkReason == '1') {
                            result = true;
                        } else if (work_mode == 'D' && employeeWorkReason == '2') {
                            result = true;
                        } else if(employeeWorkReason == '3'){
                            result = true;
                        }
                    }

                    return result;
                }

                function beforeEmpWorkSet(dialog, callback){
                    if(!dialog.tmpOnWorkInfo.reason_no && isNeedWorkReason(dialog.tmpOnWorkInfo.work_mode)){
                        loadEmpWorkReason(dialog, function(selectItem){
                            dialog.tmpOnWorkInfo.reason_no = selectItem.page_no;
                            dialog.tmpOnWorkInfo.reason_name = selectItem.page_name;
                            if (callback)
                                callback();
                        });
                    } else {
                        if (callback)
                            callback();
                    }
                }

                // 人員原因基本資料取得
                function loadEmpWorkReason(dialog, callback){
                    var query_condition_info = [{column_name:'ISSUESTATE', query_mode:'0', value:'2', merge_condition_model:'AND'}];

                    if(dialog.tmpOnWorkInfo.work_mode == 'D'){ // 下工
                        query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'1', merge_condition_model:'AND' });
                    } else if(dialog.tmpOnWorkInfo.work_mode == 'U'){ //上工
                        query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'0', merge_condition_model:'AND' });
                    }

                    $MMWService.pageNumberInfoGet({
                        page_mode : '35',
                        query_condition_info: query_condition_info
                    }, function(items){
                        if(items && items.length > 0){
                            $rootScope.showSelect({
                                label : function(item){
                                    return item.page_name + '(' + item.page_no + ')';
                                },
                                title: $filter('translate')('B0233.plz_select_reason_' + dialog.tmpOnWorkInfo.work_mode),
                                code : 'page_no',
                                selectCode : dialog.tmpOnWorkInfo.reason_no || '',
                                list : items,
                                confirm : function(selectItem, radio_dialog){
                                    radio_dialog.hide();
                                    if (callback)
                                        callback(selectItem);
                                }
                            });
                        } else {
                            $rootScope.showAlert($filter('translate')('B0233.msg.reason_empty_'+dialog.tmpOnWorkInfo.work_mode));
                        }
                    });
                }

                // 人員技能檢驗
                function inspectUserSkill(inspectInfo, feedback){
                    if(inspectInfo.employeewrokset && inspectInfo.employeewrokset.length > 0){
                        var machineInfo = inspectInfo.employeewrokset.shift();
                        if(machineInfo.work_mode == 'U'){
                            $B0231Service.init({
                                parent: inspectInfo.parent,
                                machine_no: machineInfo.machine_no,
                                machine_name: machineInfo.machine_name,
                                position_no: machineInfo.position,
                                op_no: inspectInfo.op_no,
                                area_no: inspectInfo.area_no,
                                user_no: inspectInfo.user_no,
                                user_name: inspectInfo.user_name,
                                user_title: inspectInfo.user_title,
                                releaser_verified: inspectInfo.releaser_verified,
                                feedback: function(dialog){
                                    if(dialog){
                                        inspectInfo.releaser_verified = dialog.releaser_verified;
                                        dialog.hide();
                                    }
                                    inspectUserSkill(inspectInfo, feedback);
                                },
                                req_check:function(info){ // 20231218 add by shiwl for M#0151498: 力邦合信，正式区。人员技能检核以后无记录写入数据库
                                    need_check = true;
                                    check_member = info.account;
                                }
                            });
                        }else{
                            if(feedback)
                                feedback();
                        }
                    }else{
                        if(feedback)
                            feedback();
                    }
                }

                function SMES_EmployeeWrokSet_Imp(dialog, callback){
                    var content = {
                        employeewrokset:[dialog.tmpOnWorkInfo]
                    };

                    var inspectInfo = {
                        parent: dialog.stationMachine.parent,
                        op_no: dialog.stationMachine.op_no,
                        area_no: dialog.stationMachine.pdline_no,
                        user_no: dialog.tmpOnWorkInfo.employee_no,
                        user_name: dialog.tmpOnWorkInfo.employee_name,
                        user_title: dialog.tmpOnWorkInfo.user_title,
                        releaser_verified: false,
                        employeewrokset : angular.extend([], content.employeewrokset),
                    }
                    inspectUserSkill(inspectInfo, function(){
                        SMES_EmployeeWrokSet(dialog, content, callback);
                    });
                }

                function SMES_UserInformationGet(dialog, callback){
                    dialog.tmpEmp_no = dialog.tmpEmp_no.toUpperCase();
                    var content = {
                        machine_no : dialog.stationMachine.pdline_no,
                        employee_no : dialog.tmpEmp_no,
                        report_datetime : new Date(),
                        return_type : '10'
                    };

                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_SYS.user_information_get',
                        content : content,
                        success : function(data){
                            if(callback)
                                callback(data);
                        },
                        error_callback : function(){
                            dialog.tmpOnWorkInfo = {};
                            dialog.tmpEmp_no = '';
                            dialog.ic_card = '';
                            dialog.mode = undefined;
                            dialog.beforeShown();
                        }
                    });
                }

                function SMES_EmployeeWrokSet(dialog, content, callback){
                    //20180518 modify by 李栋 for mantis#0047068

                    // 20231218 add by shiwl for M#0151498: 力邦合信，正式区。人员技能检核以后无记录写入数据库
                     if(need_check){
                         content.employeewrokset[0].need_check_skill = '1';
                         content.employeewrokset[0].skill_check_result = '0'
                         content.employeewrokset[0].skill_pass_user = check_member;
                     } else{
                        content.employeewrokset[0].need_check_skill = '0';
                        content.employeewrokset[0].skill_check_result = '1'
                        content.employeewrokset[0].skill_pass_user = '';
                     }
                     
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_SYS.employee_wrok_set_process',
                        content : content,
                        success : function(data){
                            $rootScope.showToast($filter('translate')('B0233.msg.success_'+ dialog.tmpOnWorkInfo.work_mode));
                            dialog.tmpOnWorkInfo = {};
                            dialog.tmpEmp_no = '';
                            dialog.ic_card = '';
                            if(callback)
                                callback();
                        }
                    });
                }

                $mdDialog.dialog(
                    'module/moduleB/program/B02/B0233/B0233.html',
                    function(dialog){
                        return {
                            css_url:'module/moduleB/program/B02/B0233/B0233.css',
                            parent:options.parent,
                            tmpEmp_no : '',
                            tmpOnWorkInfo : {},
                            stationMachine: options.stationMachine,
                            ic_card: '',  //IC卡
                            ICCardScanner: function () {//20200723 add by linzh for M#71988
                                $rootScope.OpenScanner({
                                    after: function (result) {
                                        $timeout(function () {
                                            dialog.ic_card = result.text;
                                            dialog.searchICCard();
                                        });
                                    },
                                    exception: function () {
                                        //目前裝置無法使用相機
                                        $rootScope.showAlert($filter('translate')('B0214.showAlert.column3'));
                                    },
                                    orientation: 'landscape'
                                });
                            },
                            searchICCard: function (event) {//20200710 add by linzh for M#71988
                                if (!event || event.keyCode == 13) {
                                    if (dialog.ic_card != '') {
                                        var content = {
                                            IcNo: dialog.ic_card
                                        }
                                        $MMWService.sendToServer({
                                            uri: 'ServicesSTD.Module_SYS.ic_card_info_get',
                                            content: content,
                                            success: function (data) {
                                                if (data.UserNo != null && data.PassWord != null) {
                                                    dialog.tmpEmp_no = data.UserNo;
                                                    dialog.searchEmp();//调用员工信息查询方法
                                                }
                                                else {
                                                    $rootScope.showAlert($filter('translate')('Login.error.ic_card_error'));
                                                    dialog.ic_card = '';
                                                    document.getElementById('ic_card').focus();
                                                }
                                            },
                                            error: function (data) {
                                                $rootScope.showAlert(data.Message);
                                                dialog.ic_card = '';
                                                document.getElementById('ic_card').focus();
                                            }
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('B0202.showAlert.column7'));
                                        dialog.ic_card = '';
                                        document.getElementById('ic_card').focus();
                                    }
                                }
                            },
                            beforeShown: function(){

                                if(config.setting.scanBarcod == "Y"){
                                    document.getElementById('ic_card').focus();
                                } else {
                                    var target = document.getElementById('tmpEmp_no');
                                    if(target)
                                        target.focus();
                                }
                               
                            },
                            searchEmp: function(event){
                                if(!event || event.keyCode==13){
                                    if(dialog.tmpEmp_no!=''){
                                        SMES_UserInformationGet(dialog, function(data){
                                            dialog.tmpOnWorkInfo = data;
                                            dialog.tmpOnWorkInfo.machine_no = options.stationMachine.pdline_no;
                                            dialog.tmpOnWorkInfo.machine_name = options.stationMachine.pdline_name;
                                            dialog.tmpOnWorkInfo.position = options.stationMachine.position_no;
                                            dialog.tmpOnWorkInfo.work_datetime = new Date();
                                            var temp = $filter('filter')(dialog.stationMachine.employee_work_detail,{employee_no:dialog.tmpOnWorkInfo.employee_no}, true);
                                            if(temp && temp.length> 0){
                                                dialog.tmpOnWorkInfo.work_mode = 'D';
                                                if(config.setting.autoWorkset)
                                                    dialog.confirm();
                                            } else {
                                                dialog.tmpOnWorkInfo.work_mode = 'U';
                                                if(config.setting.autoWorkset)
                                                    dialog.confirm();
                                            }
                                        });
                                    }else{
                                        $rootScope.showAlert($filter('translate')('B0233.msg.emp_no_empty'), function(){
                                            dialog.tmpOnWorkInfo = {};
                                            dialog.mode = undefined;
                                            dialog.beforeShown();
                                        });
                                    }
                                }
                            },
                            selectEmployee:function(item){
                                dialog.tmpEmp_no = item.employee_no;
                                dialog.searchEmp();
                            },
                            isNeedWorkReason: function(){
                                return isNeedWorkReason(dialog.tmpOnWorkInfo.work_mode);
                            },
                            isDataPrepared: function(){
                                return (dialog.tmpOnWorkInfo != null) && !angular.equals({}, dialog.tmpOnWorkInfo);
                            },
                            loadEmpWorkReason: function(){
                                loadEmpWorkReason(dialog, function(selectItem){
                                    dialog.tmpOnWorkInfo.reason_no = selectItem.page_no;
                                    dialog.tmpOnWorkInfo.reason_name = selectItem.page_name;
                                });
                            },
                            back: function () {
                                dialog.hide();
                                if(options.close)
                                    options.close();
                            },
                            confirm: function () {
                                if(!config.cache.permissions){
                                    //全權限
                                    beforeEmpWorkSet(dialog, function(){
                                        SMES_EmployeeWrokSet_Imp(dialog, function(){
                                            options.callback(dialog.beforeShown, dialog);
                                        });
                                    });
                                } else{
                                    if(config.cache.permissions.indexOf(dialog.tmpOnWorkInfo.work_mode=='U'?'B0202':'B0203')!=-1){
                                        beforeEmpWorkSet(dialog, function(){
                                            SMES_EmployeeWrokSet_Imp(dialog, function(){
                                                options.callback(dialog.beforeShown, dialog);
                                            });
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('common.msg.no_permissions'));
                                    }
                                }
                            }
                        };
                    }
                );
            };
        }]);
});
